/**
 * @author  李珂<likenamehaojie@hotmail.com>
 * @data    20170411
 * vuex types
 */

import axios from 'axios'
import * as types from '../store/types'
import router from '../router'
import qs from 'qs'
import cfg from '../properties';

// axios 配置
axios.defaults.timeout = 200000;
axios.defaults.baseURL = cfg.api_url;
// http request 拦截器
axios.interceptors.request.use(
    config => {
        const store = window._VUE_STORE_;
        try {
            store.commit(types.ALL_LOADING,true);
            config.headers['u_device_'] =qs.stringify(device);
            console.log(qs.stringify(device));

        }
        catch (e) {
        }

        console.log(store)
        if (store.state.token) {
            config.headers.Authorization = `token ${store.state.token}`;

            config.headers['m-at-id'] =`token ${store.state.token}`;
        }
        return config;
    },
    err => {
        console.log(err)
        return Promise.reject(err);
    });

// http response 拦截器
axios.interceptors.response.use(
    response => {

        console.log("==> ajax complete");
        console.log(response);

        const store = window._VUE_STORE_;
        store.commit(types.ALL_LOADING,false);
        console.log(store)
        var token = response.headers['m-at-id'];
        //  alert(token+"完成")
        if (token) {
            store.commit(types.LOGIN,{state:200,data:token});
          //  storer.save({key: 'token', value: token});
        }



        return response;
    },
    error => {
        let msg = "";
        if (error.response) {
          const store = window._VUE_STORE_;
            store.commit(types.ALL_LOADING,false);
          console.log(store)
            switch (error.response.status) {
                case 200:
                    break;
                case 401:



                    // 401 清除token信息并跳转到登录页面
                    store.commit(types.LOGOUT);
                    router.replace({
                        path: 'login',
                        query: {redirect: router.currentRoute.fullPath}
                    });
                    break;
                case 404:
                    msg = "接口不存在";
                    break;
                default:
                    try {
                        msg = error.response.data.message;
                        if (!msg) {
                            msg = error.response.data.developerMessage;
                        }
                    }
                    catch (e) {
                        // do nothing
                    }

            }
        }
        // console.log(JSON.stringify(error));//console : Error: Request failed with status code 402
        return Promise.reject(msg+"来自请求失败");
    });

export default axios;
